import {BaseModel} from './baseModel';

export interface UserToken {
  chainId: string;
  address: string;
  name: string;
  symbol: string;
  decimals: number;
  logo?: string;
  owner: string;
  type: string; // native | erc20 | spl
  amount?: string;
  uiAmount?: string;
}

export class UserTokenModel extends BaseModel {
  async createTable(): Promise<void> {
    try {
      const db = await BaseModel.getDB();
      const query = `
                CREATE TABLE IF NOT EXISTS user_token (
                    chain_id TEXT NOT NULL,
                    address TEXT NOT NULL,
                    owner TEXT NOT NULL,
                    name TEXT,
                    symbol TEXT NOT NULL,
                    decimals INTEGER NOT NULL,
                    logo TEXT,
                    type TEXT NOT NULL,
                    primary key (chain_id, address, owner)
                );
            `;
      await db.executeSql(query);
    } catch (error) {
      console.log('create table error', error);
    }
  }

  async dropTable(): Promise<void> {
    const db = await BaseModel.getDB();
    await db.executeSql('DROP TABLE IF EXISTS user_token;');
  }

  async getUserTokens(owner: string): Promise<UserToken[]> {
    const db = await BaseModel.getDB();
    const query =
      'select chain_id as chainId, address, owner, name, symbol, decimals, logo, type from user_token where owner = ?';
    const [results] = await db.executeSql(query, [owner]);

    const userTokens = results.rows.raw() as UserToken[];
    console.log('数组数组：', userTokens);
    return userTokens;
  }
}
